package com.zs4sdk.activity;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;

import com.zs4sdk.Zs4GameBase;
import com.zs4sdk.common.Extra;
import com.common.library.data.CommonHandle;
import com.common.library.entity.JSONResultEntity;
import com.zs4sdk.entity.Zs4GameData;
import com.common.library.image.MultiImageSelectorActivity;
import com.zs4sdk.jslocalobj.Zs4GameUploadFileJavascriptLocalObj;
import com.common.library.util.ActivityHelper;
import com.common.library.util.CommonWebChromeClient;
import com.common.library.util.DialogUtils;
import com.common.library.util.HandlerUtil;
import com.common.library.util.Helper;
import com.common.library.util.LogUtil;
import com.common.library.util.NetworkHelper;
import com.common.library.util.ParamsHelper;
import com.common.library.util.ProjectHelper;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;

/**
 * function: 显示webview
 *
 * @ author:linjunying
 */
public class Zs4GameShowWebViewActivity extends Zs4GameBaseWebActivity {

    private static final String TAG = Zs4GameShowWebViewActivity.class.getSimpleName();

    String title = "";
    String url = "";
    String id = "";
    String isShowSdkVersion = Extra.BOOLEAN_FALSE;
    private boolean goBackMenu = true; //是否是首页可以直接退出

    private final static int FILECHOOSER_RESULTCODE = 205;

    private final static int MY_PERMISSIONS_REQUEST_CALL_PHONE = 101;//请求打电话权限

    private final static int MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE = 102;//请求读取权限,用于打开相册获取截图

    TextView text_version;
    private ArrayList<String> mSelectPath = new ArrayList<String>();
    private String param = null;

    private DialogUtils dialogUtils;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.setContentView(ActivityHelper.getLayoutResId("zs4gamelayout_act_showwebview_menu"));

        getParams();

        init();
    }

    @Override
    public void setTitle(CharSequence title) {
        this.setTopTitle(title.toString());
    }

    @Override
    protected void init() {
        super.init();

        initReferences();

        setTopTitle(title);

        this.getWebView().getSettings().setUseWideViewPort(true);
        this.getWebView().getSettings().setJavaScriptEnabled(true);
        this.getWebView().getSettings().setLoadWithOverviewMode(true);
        this.getWebView().getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        this.getWebView().setWebChromeClient(new CommonWebChromeClient(this) {
            /**
             * Notify the host application of a change in the document title.
             *
             * @param view  The WebView that initiated the callback.
             * @param title A String containing the new title of the document.
             */
            @Override
            public void onReceivedTitle(WebView view, String title) {
                setTopTitle(title);
                super.onReceivedTitle(view, title);
            }
        });
        this.getWebView().addJavascriptInterface(new Zs4GameUploadFileJavascriptLocalObj(
                new Zs4GameUploadFileJavascriptLocalObj.zs4gameUploadFileJavascriptCallback() {
                    @Override
                    public void uploadfile() {
                        goToSelectPhotos();
                    }

                    @Override
                    public void account_submit(String data) {
                        submitqa(data, "account_submit");
                    }

                    @Override
                    public void problem_submit(String data) {
                        submitqa(data, "problem_submit");
                    }

                }), "local_obj");

        //未接网络提示
        if (!NetworkHelper.isNetworkAvailable(this)) {
            ActivityHelper.showToast(ActivityHelper.getStringResId("zs4gamestring_hint_has_not_network"));
        } else {
            HandlerUtil.sendMessage(myHandle, Extra.MessageKey.SHOWPROCESS_CANCANCEL);
            getWebView().loadUrl(url, getHeader());
//            getWebView().loadUrl("https://www.baidu.com");
            Log.e("url"," webView url is "+url);
        }

        if (Extra.BOOLEAN_TRUE.equals(isShowSdkVersion)) {
            text_version.setText(Zs4GameBase.getInstance().getVersion());
            text_version.setVisibility(View.VISIBLE);
        } else {
            text_version.setVisibility(View.GONE);
        }
    }

    public void submitqa(String data, String urltype) {
        if ((getTimestamp() - Zs4GameData.getInstance().getKefuTime()) >= 60) {
            Zs4GameData.getInstance().setKefuTime(getTimestamp());
            if (NetworkHelper.isNetworkAvailable(Zs4GameShowWebViewActivity.this)) {
                try {
                    param = URLDecoder.decode(data, "utf-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                Message msg = myHandle.obtainMessage();

                Bundle bundle = new Bundle();
                bundle.putString("url_type", urltype);
                msg.setData(bundle);


                msg.what = FILECHOOSER_RESULTCODE;
                myHandle.sendMessage(msg);
            } else {
                ActivityHelper.showToast(ActivityHelper.getStringResId("zs4gamestring_hint_has_not_network"));
            }
        } else {
            ActivityHelper.showToast(ActivityHelper.getStringResId("zs4gamestring_text_sumbitqa_too_more"));
        }
//                        submitQA();
    }

    private void goToSelectPhotos() {

        if (Build.VERSION.SDK_INT >= 23 && ContextCompat.checkSelfPermission(this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            // 判断是否需要解释获取权限原因
            //不需要解释直接请求

                dialogUtils = new DialogUtils(this,
                        ActivityHelper.getString(ActivityHelper.getStringResId("zs4gamestring_text_dialog_need_read_permission")),
                        ActivityHelper.getString(ActivityHelper.getStringResId("zs4gamestring_text_dialog_goto_set")),
                        ActivityHelper.getString(ActivityHelper.getStringResId("zs4gamestring_text_dialog_dont_upload")),
                        new DialogUtils.LeaveDialogListener() {
                            @Override
                            public void onClick(View view) {
                                int id = view.getId();
                                if (ActivityHelper.getIdResId("zs4gameviewid_dialog_btn_cannel") == id) {
                                    dialogUtils.dismiss();
                                }
                                if (ActivityHelper.getIdResId("zs4gameviewid_dialog_btn_sure") == id) {
                                    ActivityHelper.openSetting(Zs4GameShowWebViewActivity.this);
                                    dialogUtils.dismiss();
                                }
                            }
                        });
                dialogUtils.show();
        } else {
            Intent intent1 = new Intent(Zs4GameShowWebViewActivity.this, Zs4GameSelectImageActivity.class);
            intent1.putStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT, (ArrayList<String>) mSelectPath.clone());
            startActivityForResult(intent1, Extra.RESULTCODE.WEB_VIEW_UPLOAD_CODE);
        }
    }


    private ArrayList<NameValuePair> setParam(String parm) {

        ArrayList<NameValuePair> paramList = new ArrayList<NameValuePair>();

        String[] tmp_parm = parm.split("&");
        for (int i = 0; i < tmp_parm.length; i++) {
            String[] sub = tmp_parm[i].split("=");
            if (sub.length == 2) {
                paramList.add(new BasicNameValuePair(sub[0], sub[1]));
            } else if (sub.length == 1) {
                paramList.add(new BasicNameValuePair(sub[0], ""));
            }

        }

//        Pattern p = Pattern.compile("&(\\w+)=");
//        Matcher m = p.matcher(tmp_parm);
//
//        while (m.find()) {
//            Pattern p2 = Pattern.compile(m.group(1) + "=(.*?)&",Pattern.MULTILINE);
//            Matcher m2 = p2.matcher(tmp_parm);
//            if (m2.find()) {
//                paramList.add(new BasicNameValuePair(m.group(1), m2.group(1)));
//            } else {
//                paramList.add(new BasicNameValuePair(m.group(1), ""));
//            }
//        }
        return paramList;

    }

    private String getUrlByType(String urltype) {
        String url = "";
        if (urltype.equals("problem_submit")) {
            url = Extra.URL.UPLAOD_IMAGE_PROMBLE;
        } else if (urltype.equals("account_submit")) {
            url = Extra.URL.UPLAOD_IMAGE_ACCOUNT;
        }
        return url;
    }

    private void submitQA(String urltype) {
        String result = "";

        HandlerUtil.sendMessage(myHandle, Extra.MessageKey.SHOWPROCESS);
        ArrayList<File> files = new ArrayList<File>();
        if (Helper.isNotNull(mSelectPath)) {
            for (int i = 0; i < mSelectPath.size(); i++) {
                File file = new File(mSelectPath.get(i));
                files.add(file);
            }
        } else {
            files = null;
        }

        String Url = getUrlByType(urltype);

        if (Helper.isNotEmpty(Url)) {
            try {
                result = NetworkHelper.upload(Url, setParam(param), files,
                        "image",
                        ParamsHelper.getUserAgent1());
            } catch (Exception e) {
                e.printStackTrace();
            }

            Message msg = myHandle.obtainMessage();
            msg.what = Extra.MessageKey.REQUEST_SUCCESS;
            msg.obj = result;
            // 发送消息
            myHandle.sendMessage(msg);

        } else {
            ActivityHelper.showToast("url is empty");
        }

    }

    CommonHandle myHandle = new CommonHandle(Zs4GameShowWebViewActivity.this, new CommonHandle.HandleMessage() {

        @Override
        public void doHandleMessage(Message msg) {
            HandlerUtil.sendMessage(myHandle, Extra.MessageKey.DISMISSPROCESS);
            if (Extra.MessageKey.REQUEST_SUCCESS == msg.what) {
                JSONResultEntity entity = new JSONResultEntity((String) msg.obj);

                // 1 表示上传成功
                if (entity.getResult() == 1) {
                    mSelectPath.clear();
                    getWebView().loadUrl(url, getHeader());
                    ActivityHelper.showToast(entity.getDesc());
                    goBackMenu = true;
                }
                // 0 表示上传失败 停留在当前页面 不刷新
                else if (entity.getResult() == 0) {
                    ActivityHelper.showToast(entity.getDesc());
                }
                // 2 表示有问题,刷新当前页面(预留)
                else if (entity.getResult() == 2) {
                    mSelectPath.clear();
                    getWebView().reload();
                    ActivityHelper.showToast(entity.getDesc());
                }
                // 3 表示有问题,重新载入客服首页(预留)
                else if (entity.getResult() == 3) {
                    mSelectPath.clear();
                    getWebView().loadUrl(url, getHeader());
                    ActivityHelper.showToast(entity.getDesc());
                    goBackMenu = true;
                }
            } else if (FILECHOOSER_RESULTCODE == msg.what) {

                final String url_type = Helper.isNotNull(msg.getData()) ? msg.getData().getString("url_type") : "";

                new Thread() {
                    @Override
                    public void run() {
                        submitQA(url_type);
                    }
                }.start();
            }
        }
    });


    /**
     * function: 得到参数
     *
     * @ author:linjunying 2013-3-23 上午9:38:01
     */
    private void getParams() {

        Intent intent = getIntent();
        if (null != intent) {
            if (intent.hasExtra(Extra.INTENTKEY.TITLE)) {
                title = intent.getStringExtra(Extra.INTENTKEY.TITLE);
            }
            if (intent.hasExtra(Extra.INTENTKEY.URL)) {
                url = intent.getStringExtra(Extra.INTENTKEY.URL);
            }
            if (intent.hasExtra(Extra.INTENTKEY.FLAG)) {
                flag = intent.getStringExtra(Extra.INTENTKEY.FLAG);
            }
            if (intent.hasExtra(Extra.INTENTKEY.ISSHOW_SDKVERSION)) {
                isShowSdkVersion = intent.getStringExtra(Extra.INTENTKEY.ISSHOW_SDKVERSION);
            }
        }
    }

    @Override
    protected WebViewClient createWebViewClient() {
        WebViewClient webViewClient = new WebViewClient() {

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                LogUtil.d(TAG, "shouldOverrideUrlLoading: " + url);
//				return super.shouldOverrideUrlLoading(view, url);

                if (url.endsWith(".apk")) {
                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                    startActivity(intent);
                    return true;
                } else if (url.startsWith("tel:")) {
                    doCallPhone(url);
                    return true;
                } else if (url.startsWith("mqqwpa:")) {

                    // 判断qq-apk是否存在
                    if (ProjectHelper.checkApkExist(Zs4GameShowWebViewActivity.this, "com.tencent.mobileqq")) {
                        startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
                    } else {
                        ActivityHelper.showToast("请先下载并安装QQ客户端");
                    }
                    return true;
                }
                goBackMenu = false;


                if (url.contains(Extra.URL.SDKGAME_HOST_SELECT)) {
                    if(url.contains("http://ins.zs4game.com/feedback.php")){
                        Log.e("sub"," header is");
                        HashMap<String, String> mHeaderMap = new HashMap<String, String>();
                        if (!mHeaderMap.containsKey(Extra.NETWORK_KEY_USER_AGENT1)){
                            mHeaderMap.put("USER-AGENT1", ParamsHelper.getUserAgent1());
                        }
                        getWebView().loadUrl(url, mHeaderMap);
                    }else{
                        getWebView().loadUrl(url, getHeader());
                    }

                    return true;
                } else {
                    return super.shouldOverrideUrlLoading(view, url);
                }
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                LogUtil.d(TAG, "onPageFinished:" + url);
                setTopTitle(mWebView.getTitle());
                super.onPageFinished(view, url);
                HandlerUtil.sendMessage(myHandle, Extra.MessageKey.DISMISSPROCESS);
            }

        };
        return webViewClient;
    }


    private void initReferences() {

        text_version = findView(TextView.class, ActivityHelper.getIdResId("zs4gameviewid_web_text_version"));

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode,
                                    Intent intent) {

        if (requestCode == Extra.RESULTCODE.WEB_VIEW_UPLOAD_CODE) {
            if (resultCode == Activity.RESULT_OK) {
                if (intent == null) {
                } else {
                    mSelectPath = intent.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);
                }
            }
        }
    }
    @Override
    protected  int getLeftBtnType() {
//        LogUtil.e("==========99999999",flag);
        if(Extra.FLAG_MENU.equals(flag) || Extra.FLAG_MANUAL_MENU.equals(flag)) {
            return TYPE_LEFTBTN_BACKTOMENU;
        }else if(Extra.FLAG_MENU_ACCOUNT.equals(flag)){
            return TYPE_LEFTBTN_BACK;
        }else  if(getPackageName().concat(Extra.ACTIONKEY.VOUCHERCENTER_POSTFIX).equals(flag)||
                getPackageName().concat(Extra.ACTIONKEY.CLOSEACTIVITY_POSTFIX_MENU).equals(flag)){
            return TYPE_LEFTBTN_BACKTOGAME;
        }
        else {
            return TYPE_LEFTBTN_BACK;
        }
    }

    @Override
    public void onBackPressed() {
        if(goBackMenu){
            backToGame();
            return;
        }
        if (mSelectPath != null) {
            mSelectPath.clear();
        }
        if (mWebView.canGoBack()) {
            mWebView.goBack();// 返回前一个页面
            return;
        }
        super.onBackPressed();
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (mSelectPath != null) {
            mSelectPath.clear();
        }
//        if (keyCode == KeyEvent.KEYCODE_BACK && mWebView.canGoBack() && goBackMenu == false) {
//            mWebView.goBack();// 返回前一个页面
//            return true;
//        }
        if(goBackMenu){
            backToGame();
            return true;
        }
        if (mWebView.canGoBack()) {
            mWebView.goBack();// 返回前一个页面
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 取得当前时间戳
     *
     * @return
     */
    private long getTimestamp() {
        return System.currentTimeMillis() / 1000L;
    }


    private void doCallPhone(String url) {

        if (Build.VERSION.SDK_INT >= 23 && ContextCompat.checkSelfPermission(this,
                Manifest.permission.CALL_PHONE)
                != PackageManager.PERMISSION_GRANTED) {
            // 判断是否需要解释获取权限原因
            if (!ActivityCompat.shouldShowRequestPermissionRationale(this,
                    Manifest.permission.CALL_PHONE)) {
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.CALL_PHONE},
                        MY_PERMISSIONS_REQUEST_CALL_PHONE);
            } else {
                dialogUtils = new DialogUtils(this,
                        ActivityHelper.getString(ActivityHelper.getStringResId("zs4gamestring_text_dialog_need_call_permission")),
                        ActivityHelper.getString(ActivityHelper.getStringResId("zs4gamestring_text_dialog_goto_set")),
                        ActivityHelper.getString(ActivityHelper.getStringResId("zs4gamestring_text_dialog_dont_call")),
                        new DialogUtils.LeaveDialogListener() {
                            @Override
                            public void onClick(View view) {
                                int id = view.getId();
                                if (ActivityHelper.getIdResId("zs4gameviewid_dialog_btn_cannel") == id) {
                                    dialogUtils.dismiss();
                                }
                                if (ActivityHelper.getIdResId("zs4gameviewid_dialog_btn_sure") == id) {
                                    ActivityHelper.openSetting(Zs4GameShowWebViewActivity.this);
                                    dialogUtils.dismiss();
                                }
                            }
                        });
                dialogUtils.show();
            }
        } else {
            Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse(url));
            startActivity(intent);
        }
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        if (requestCode == MY_PERMISSIONS_REQUEST_CALL_PHONE) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            } else {
//                ActivityHelper.showToast("没有权限无法拨打电话哦~");
            }
            return;
        } else if (requestCode == MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                goToSelectPhotos();
            } else {
//                ActivityHelper.showToast("没有权限无法拨打电话哦~");
            }
            return;
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == ActivityHelper.getIdResId("zs4gameviewid_mLeftView_view_titlebar")) {
            onBackPressed();
        } else if (v.getId() == ActivityHelper.getIdResId("zs4gameviewid_mRightView_view_titlebar")) {
            if (TYPE_RIGHTBTN_BACKTOGMAGE == type_rightbtn) {
                if (mSelectPath != null) {
                    mSelectPath.clear();
                }
                backToGame();
            }
        }
//        super.onClick(v);
    }
}
